home *** CD-ROM | disk | FTP | other *** search
/ Languguage OS 2 / Languguage OS II Version 10-94 (Knowledge Media)(1994).ISO / gnu / wdiff004.lha / wdiff-0.04 / readpipe.c < prev    next >
C/C++ Source or Header  |  1992-12-05  |  2KB  |  76 lines

  1. /* Open a pipe to read from a program without intermediary sh.
  2.    Copyright (C) 1992 Free Software Foundation, Inc.
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 2, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  17.  
  18. /* Written by David MacKenzie.  */
  19.  
  20. #include <stdio.h>
  21. #include <varargs.h>
  22.  
  23. #if defined (HAVE_UNISTD_H)
  24. #include <unistd.h>
  25. #endif
  26.  
  27. /* Open a pipe to read from a program without intermediary sh.
  28.    Checks PATH.
  29.    Sample use:
  30.    stream = readpipe ("progname", "arg1", "arg2", (char *) 0);
  31.    Return 0 on error. */
  32.  
  33. /* VARARGS */
  34. FILE *
  35. readpipe (va_alist)
  36.   va_dcl
  37. {
  38.   int fds[2];
  39.   va_list ap;
  40.   char *args[100];
  41.   int argno = 0;
  42.  
  43.   /* Copy arguments into `args'. */
  44.   va_start (ap);
  45.   while ((args[argno++] = va_arg (ap, char *)) != NULL)
  46.     /* Do nothing. */ ;
  47.   va_end (ap);
  48.  
  49.   if (pipe (fds) == -1)
  50.     return 0;
  51.  
  52.   switch (fork ())
  53.     {
  54.     case 0:            /* Child.  Write to pipe. */
  55.       close (fds[0]);        /* Not needed. */
  56.       if (fds[1] != 1)        /* Redirect 1 (stdout) only if needed.  */
  57.     {
  58.       close (1);        /* We don't want the old stdout. */
  59.       if (dup (fds[1]) == 0)/* Maybe stdin was closed. */
  60.         {
  61.           dup (fds[1]);    /* Guaranteed to dup to 1 (stdout). */
  62.           close (0);
  63.         }
  64.       close (fds[1]);    /* No longer needed. */
  65.     }
  66.       execvp (args[0], args);
  67.       _exit (2);        /* 2 for `cmp'. */
  68.     case -1:            /* Error. */
  69.       return 0;
  70.     default:            /* Parent.  Read from pipe. */
  71.       close (fds[1]);        /* Not needed. */
  72.       return fdopen (fds[0], "r");
  73.     }
  74.   /* NOTREACHED */
  75. }
  76.